package com.mxchip.livestar.repository

import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.provider.CallLog
import android.provider.ContactsContract
import android.text.TextUtils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.mxchip.livestar.base.RecentCallBean
import com.mxchip.livestar.base.SingletonHolder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.*


class CallLogRepository private constructor(context: Context) {

    //获取手机通讯录联系人
    companion object : SingletonHolder<CallLogRepository, Context>(::CallLogRepository)

    private val contentResolver: ContentResolver = context.contentResolver

    private val callLogList: MutableLiveData<List<RecentCallBean>> by lazy {
        MutableLiveData<List<RecentCallBean>>(arrayListOf())
    }

    val all: LiveData<List<RecentCallBean>>
        get() = callLogList

    init {
        reload()
    }

    fun reload(){
        GlobalScope.launch(Dispatchers.Main) {
            val list = reloadAll()
            callLogList.value = list
        }
    }

    fun insert(number: String, name: String?, duration: String, type: String, isNew: String) {
        GlobalScope.launch(Dispatchers.Main) {
            mInsert(number, name, duration, type, isNew)
            val list = reloadAll()
            callLogList.value = list
        }
    }

    @SuppressLint("MissingPermission")
    private suspend fun mInsert(number: String, name: String?, duration: String, type: String, isNew: String) = withContext(Dispatchers.IO) {
        val values = ContentValues()
        values.put(CallLog.Calls.NUMBER, number)
        if (!name.isNullOrBlank()) {
            values.put(CallLog.Calls.CACHED_NAME, name)
        }
        values.put(CallLog.Calls.DATE, System.currentTimeMillis())
        values.put(CallLog.Calls.DURATION, duration)
        values.put(CallLog.Calls.TYPE, type)
        values.put(CallLog.Calls.NEW, isNew)
        contentResolver.insert(CallLog.Calls.CONTENT_URI, values)
    }

    suspend fun getContactNameByNumber(number: String): String? = withContext(Dispatchers.IO) {
        var name: String? = null
        val pCur = contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?", arrayOf(number), null)
        if (pCur != null && pCur.moveToFirst()) {
            val columnIndex = pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
            name = pCur.getString(columnIndex)
        }
        name
    }


    fun deleteById(id: String) {
        GlobalScope.launch(Dispatchers.Main) {
            mDeleteById(id)
            val list = reloadAll()
            callLogList.value = list
        }
    }

    @SuppressLint("MissingPermission")
    private suspend fun mDeleteById(id: String) = withContext(Dispatchers.IO) { //根据姓名求id
        contentResolver.delete(CallLog.Calls.CONTENT_URI, CallLog.Calls._ID + " = ? ", arrayOf(id))
    }

    @SuppressLint("MissingPermission")
    private suspend fun reloadAll():List<RecentCallBean> = withContext(Dispatchers.IO) {

        val list: MutableList<RecentCallBean> = arrayListOf()

        val cs: Cursor? = contentResolver.query(CallLog.Calls.CONTENT_URI, arrayOf(
                CallLog.Calls.CACHED_NAME,  //姓名
                CallLog.Calls.NUMBER,  //号码
                CallLog.Calls.TYPE,  //呼入/呼出(2)/未接
                CallLog.Calls.DATE,  //拨打时间
                CallLog.Calls.DURATION,  //通话时长
                CallLog.Calls._ID
        ), null, null,  "${CallLog.Calls.DEFAULT_SORT_ORDER} LIMIT 50")

        if (cs != null && cs.count > 0) {
            cs.moveToFirst()
            while (!cs.isAfterLast) {
                val recent = RecentCallBean()
                var callName = cs.getString(0)
                val callNumber = cs.getString(1)
                var pCur: Cursor? = null
//                if (TextUtils.isEmpty(callName)) {
                    try {
                        pCur = contentResolver.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?", arrayOf(callNumber), null)
                        if (pCur != null && pCur.moveToFirst()) {
                            val columnIndex = pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                            callName = pCur.getString(columnIndex)
                        }else{
                            callName="";
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    } finally {
                        pCur?.close()
                    }
//                }
                //通话类型
                val callType = cs.getString(2).toInt()
                var callTypeStr = ""
                when (callType) {
                    CallLog.Calls.INCOMING_TYPE -> callTypeStr = "呼入"
                    CallLog.Calls.OUTGOING_TYPE -> callTypeStr = "呼出"
                    CallLog.Calls.MISSED_TYPE -> callTypeStr = "未接"
                }
                val callDate = Date(cs.getString(3).toLong())
                //                String callDateStr=sdf.format(callDate);
                val callDateStr = format(callDate)
                //通话时长
                val callDuration = cs.getString(4).toInt()
                val min = callDuration / 60
                val sec = callDuration % 60
                val callId = cs.getString(5)
                val callDurationStr =  "$min 分 $sec 秒"
                val callOne = ("ID: $callId, 类型：$callTypeStr, 称呼：$callName, 号码：$callNumber, 通话时长：$callDurationStr, 时间:$callDateStr\n---------------------\n")
//                Log.e("CallLogRepository", "callOne: $callOne")

                recent.id = callId
                recent.number = callNumber
                recent.name = callName
                recent.time = callDateStr
                recent.callTypeString = callTypeStr
                recent.callType = callType
                list.add(recent)
                cs.moveToNext()
            }

            cs.close()
        }

        return@withContext list
    }


    private fun format(callDate: Date): String { //        timeStamp 毫秒值
        val timeStamp = callDate.time
        //拨打时间
        val sdf = SimpleDateFormat("HH:mm")
        val date_sdf = SimpleDateFormat("yyyy/MM/dd HH:mm")
        val format = sdf.format(timeStamp)
        val date_format = date_sdf.format(timeStamp)
        val curTimeMillis = System.currentTimeMillis()
        val curDate = Date(curTimeMillis)
        val todayHoursSeconds = curDate.hours * 60 * 60
        val todayMinutesSeconds = curDate.minutes * 60
        val todaySeconds = curDate.seconds
        val todayMillis = (todayHoursSeconds + todayMinutesSeconds + todaySeconds) * 1000
        val todayStartMillis = curTimeMillis - todayMillis
        return if (timeStamp >= todayStartMillis) {
            format
        } else date_sdf.format(Date(timeStamp))
    }


}